<template>
  <div id="myThree"></div>
</template>
<script setup>
import * as THREE from "three";
import { onMounted } from "vue";
onMounted(() => {
  init();
});
function init() {
  const w = window.innerWidth;
  const h = window.innerHeight;
  //场景
  /**
   * webgl 7种图元 一切的3d的东西都是由三角形组成
   * 场景由那些组成
   *  point 点
   * line 线
   * Mesh 面（体）
   *    geometry   几何体
   *    material   材质
   * light 灯光
   *
   */
  const scene = new THREE.Scene();

  //加一个辅助
  const axes = new THREE.AxesHelper(2, 2, 2);
  scene.add(axes);

  // 东西 家电、家具
  //物体 geometry(几何体或者骨架) + material(材质、皮肤)
  const geometry = new THREE.BoxGeometry(1, 1, 1);
  const material = new THREE.MeshBasicMaterial();
  const cube = new THREE.Mesh(geometry, material);
  scene.add(cube);

  //Position
  // cube.position.set(0, 0, 0);
  // //Rotation
  // cube.rotation.x = (45 / 180) * Math.PI;
  // cube.rotation.y = (45 / 180) * Math.PI;

  // //Scale
  // cube.scale.set(2, 2, 2);
  // console.log(cube.scale);
  //光线
  // const light = new THREE.AmbientLight();
  // scene.add(light);
  //相机
  const camera = new THREE.PerspectiveCamera(75, w / h, 0.1, 100);
  camera.position.set(0, 0, 5);
  camera.lookAt(0, 0, 0);

  //渲染器
  const renderer = new THREE.WebGLRenderer()
  renderer.setSize(w, h);
  // renderer.render(scene, camera);
  document.querySelector("#myThree").append(renderer.domElement);
  /**
   * 接下来做变换  -属性的操作
   * transform
   * 1、position 位置
   * 2、rotation 旋转
   * 3、scale 缩放
   *
   * three.js 的坐标系
   */

  //动起来,用这个不是觉得1000/60 的视时间 因为没有考虑 运算的时间
  // let i = 0;
  // setInterval(() => {
  //   cube.rotation.z += 0.01;
  //   renderer.render(scene, camera);
  // }, 1000 / 60);

  //requestAnimationFrame
  // function tick(){
  //   cube.rotation.z += 0.01;
  //   renderer.render(scene, camera);
  //   requestAnimationFrame(tick)
  // }
  // tick()
  //60hz 60 * 0.01 = .6
  //120hz 120 * 0.01 = 1.2
  //解决不同刷新率的问题
  // let time = Date.now()
  // function tick(){
  //   const current = Date.now()
  //   let deltaTime = current - time
  //   time = current
  //   cube.rotation.z += deltaTime * 0.001
  //   renderer.render(scene,camera)
  //   requestAnimationFrame(tick)

  // }
  // tick()

  const clock = new THREE.Clock();
  tick();
  function tick() {
    const time = clock.getElapsedTime();
    // cube.rotation.z = time;
    cube.position.x = Math.sin(time * 2) * 2;
    cube.position.y = Math.cos(time * 2) * 2;
    requestAnimationFrame(tick);
    renderer.render(scene, camera);
  }
}
</script>
